//
//  ClearCls.m

//
//  Created by ecsage on 16/11/30.
//  Copyright © 2016年 ecsage. All rights reserved.
//

#import "ClearCls.h"

@implementation ClearCls

#pragma mark - 计算缓存大小
+ (CGFloat)calculateCache
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    CGFloat cacheSize = [self folderSizeAtPath:cachPath];
    
    return cacheSize;
}

#pragma mark 遍历文件夹获得文件夹大小，返回多少M
+ (CGFloat)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1000.0*1000.0);
}

#pragma mark 单个文件的大小
+ (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

#pragma mark - 清除缓存
// 清除缓存
+ (void)clearCacheWithSuccessBlock:(clearCacheSuccessBlock)successBlock {
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    for (NSString *p in files) {
        NSError *error;
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
    
    // 清除tmp文件
    NSString *tmpPath = NSTemporaryDirectory();
    NSArray *tmpPathFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tmpPath error:NULL];
    NSEnumerator *e = [tmpPathFiles objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        [kFileManager removeItemAtPath:[tmpPath stringByAppendingPathComponent:filename] error:NULL];
    }
    
    // 清除图片内存缓存
//    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [self performSelectorOnMainThread:@selector(clearCacheSuccess:) withObject:successBlock waitUntilDone:YES];
    
}

+ (void)clearCacheSuccess:(clearCacheSuccessBlock)successBlock {
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(successBlock){
            successBlock();
        }
        
    });
}

@end
